import {Component, OnInit} from '@angular/core';
import {LoginUserService} from '../../services/login-user.service';
import {UserMenu} from '../../entities/user/user-menu';
import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd/message';
import {LoginUser} from '../../entities/user/login-user';
import {AppRoutingCache} from '../../rootStrategy/app-routing-cache';

@Component({
  selector: 'app-welcome',
  templateUrl: './welcome.component.html',
  styleUrls: ['./welcome.component.less']
})
export class WelcomeComponent implements OnInit {
  isCollapsed = false;

  menus: UserMenu[];
  loginUser: LoginUser;

  constructor(private loginUserService: LoginUserService, private router: Router, private msg: NzMessageService) {
  }

  ngOnInit(): void {
    this.getMenus();
    this.loginUser = this.loginUserService.currentUser;
  }

  getMenus(): void {
    this.loginUserService.MENUS.subscribe(value => {
      this.menuListToMap(value);
    }, error => {
      if (error.status === 401) {
        this.router.navigate(['/login']).then(() => {
          this.msg.error('未登陆或登陆超时!');
        });
      } else {
        if (error.error?.status === 'TOKE_EXPIRED') {
          this.router.navigate(['/login']).then(() => {
            this.msg.error('未登陆或登陆超时!');
          });
        } else {
          this.msg.error('查询菜单时发生错误！');
        }
      }
    });
  }

  logout(): void {
    this.loginUserService.clean();
    this.loginUserService.logout();
    this.router.navigate(['/login']).then(() => {
      AppRoutingCache.cleanRouteSnapshot();
      this.msg.info('退出成功!');
    });
  }


  menuListToMap(menuList: UserMenu[] = []): void {
    if (!menuList.length) {
      return;
    }
    const menuMap: { [pid: string]: UserMenu } = {};
    const topMenuArray: UserMenu[] = [];
    for (const item of menuList) {
      item.expand = true;
      menuMap[item.pid] = item;
      if (!item.parentId) {
        topMenuArray.push(item);
      }
    }

    // 构造层级关系
    for (const item of menuList) {
      if (item.parentId) {
        const parent = menuMap[item.parentId];
        if (parent) {
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(item);
        } else {
          item.parentId = null;
        }
      }
    }
    this.menus = topMenuArray;
    for (const item of this.menus) {
      item.level = 0;
      this.setLevel(item.children, 0);
    }
  }

  setLevel(menus: UserMenu[], level: number): void {
    if (!menus || !menus.length) {
      return;
    }
    for (const item of menus) {
      item.level = level + 1;
      this.setLevel(item.children, level + 1);
    }
  }

}
